package com.jwgf.wifihotspot;

import com.jwgf.excel.ShiftReport2Excel;
import com.jwgf.objectbox.ShiftReport;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class UDPReceiver {
    private static UDPReceiver instance;
    private DatagramSocket ds;

    public static UDPReceiver getInstance() {
        if (instance == null) {
            instance = new UDPReceiver();
        }
        return instance;
    }

    private UDPReceiver() {
    }

    public void start() {
        try {
            ds = new DatagramSocket(6666);
            byte[] buf = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buf, buf.length);
            Observable.just(1).observeOn(Schedulers.io())
                    .subscribe(new Consumer<Integer>() {
                        @Override
                        public void accept(Integer integer) throws Throwable {
                            while (true) {
                                ds.receive(dp);
                                StringBuilder sb = new StringBuilder();
                                sb.append("ip:").append(dp.getAddress().getHostAddress()).append("\n");
                                sb.append("port:").append(dp.getPort()).append("\n");
                                sb.append("length:").append(dp.getLength()).append("\n");
                                sb.append("data:").append(new String(dp.getData(), 0, dp.getLength()));
                                System.out.println(sb.toString());
//                                ShiftReport2Excel.createExcelFile();

                            }
                        }
                    });
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        ds.close();
    }
}
